﻿

using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

using Gift.DAL;
using Gift.Model;
using System.Data;
using System.Text;
using System.Xml;
using Gift.WebApp;


namespace WebApp.admin.goods
{
    public partial class goodsList : BaseAdmin
    {

        protected string kw = "";
        protected string order = "id";
        protected int ot = 1;
        protected int pageCount = 0;
        protected int pageIndex = 1;
        protected int pageSize = 20;
        protected PageList pl = new PageList();
        protected int t = 0;
        protected int total = 0;

        string _addDisplay = "none";

        public string AddDisplay
        {
            get { return _addDisplay; }
        }
        bool _isEdit = false;
        bool _isDeleted = false;
        bool _isGoodsIn = false;
        bool _isGoodsOut = false;
        string _agentTypeValue1 = string.Empty;
        string _agentTypeValue0 = "checked=\"checked\"";

        public string AgentTypeValue1
        {
            get {
                
                return _agentTypeValue1; }
        
        }
        public string AgentTypeValue0
        {
            get
            {

                return _agentTypeValue0;
            }

        }

        // Methods
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            DataTable goodGalleryByGoods;
            string pathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
            string str2 = base.Request.Form["Item"];
            if (str2.Contains(","))
            {
                Array array = str2.Split(new char[] { ',' });
                foreach (string str3 in array)
                {
                    goodGalleryByGoods = BaseFactory.theGoodGallery.GetGoodGalleryByGoods(Convert.ToInt32(str3));
                    if (BaseFactory.theGoods.Delete(Convert.ToInt32(str3)))
                    {
                        foreach (DataRow row in goodGalleryByGoods.Rows)
                        {
                            if ((row["thumbImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["thumbImg"].ToString())))
                            {
                                File.Delete(base.Server.MapPath(row["thumbImg"].ToString()));
                            }
                            if ((row["smallImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["smallImg"].ToString())))
                            {
                                File.Delete(base.Server.MapPath(row["smallImg"].ToString()));
                            }
                            if ((row["bigImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["bigImg"].ToString())))
                            {
                                File.Delete(base.Server.MapPath(row["bigImg"].ToString()));
                            }
                        }
                    }
                }
            }
            else
            {
                goodGalleryByGoods = BaseFactory.theGoodGallery.GetGoodGalleryByGoods(Convert.ToInt32(str2));
                if (BaseFactory.theGoods.Delete(Convert.ToInt32(str2)))
                {
                    foreach (DataRow row in goodGalleryByGoods.Rows)
                    {
                        if ((row["thumbImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["thumbImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["thumbImg"].ToString()));
                        }
                        if ((row["smallImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["smallImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["smallImg"].ToString()));
                        }
                        if ((row["bigImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["bigImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["bigImg"].ToString()));
                        }
                    }
                }
            }
            base.Response.Redirect(pathAndQuery);
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                string term = "";
                if ((base.Request.QueryString["t"] != null) && (base.Request.QueryString["kw"] != null))
                {
                    this.kw = base.Request.QueryString["kw"];
                    if (base.Request.QueryString["t"] != "categoryName")
                    {
                        term = base.Request.QueryString["t"] + " like '%" + this.kw + "%' ";
                    }
                    else
                    {
                        term = "tbGoods.id in(select goods from tb_goodsCategory a left join tb_category b on a.category=b.categoryIdentity where b.categoryName like '%" + this.kw + "%') ";
                    }
                }

                ExcelHelper.ExportDataTableToExcel(BaseFactory.theGoods.GetAllGoodsByTerm(term), DateTime.Now.ToString("yyyyMMddHHmmssffffff") + ".xls", "商品列表");
            }
            catch
            {
            }
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                string filename = base.Server.MapPath("/cn/excel/" + DateTime.Now.ToString("yyyyMMddHHmmssffffff") + Path.GetExtension(this.fileExcel.PostedFile.FileName));
                this.fileExcel.PostedFile.SaveAs(filename);
                DataTable table = ExcelHelper.ImportDataTableFromExcel(filename, "商品列表", 0);
                ArrayList list = new ArrayList();
                int num = 0;
                int id = 0;
                foreach (DataRow row in table.Rows)
                {
                    tbGoodsCategory category;
                    tbGoodsEntitys entitys;
                    tbGoods goods = new tbGoods();
                    if (row["商品序号"].ToString() != "")
                    {
                        goods.id = Convert.ToInt32(row["商品序号"]);
                        if ((((((row["商品分类"].ToString() != "") && (row["品牌"].ToString() != "")) && ((row["是否精品"].ToString() != "") && (row["是否新品"].ToString() != ""))) && (((row["是否上架"].ToString() != "") && (row["是否热销"].ToString() != "")) && ((row["是否打折促销"].ToString() != "") && (row["是否参与会员打折"].ToString() != "")))) && ((((row["是否订单满额免运费"].ToString() != "") && (row["是否订单满额打折"].ToString() != "")) && ((row["是否订单满额减少"].ToString() != "") && (row["是否订单满额赠送礼品"].ToString() != ""))) && ((row["是否订单满额赠送积分"].ToString() != "") && (row["是否免运费"].ToString() != "")))) && (row["运费模版"].ToString() != ""))
                        {
                            goods.category = row["商品分类"].ToString();
                            goods.brand = Convert.ToInt32(row["品牌"]);
                            goods.goodsName = row["商品名称"].ToString();
                            goods.goodsNo = row["商品编号"].ToString();
                            goods.origin = row["产地"].ToString();
                            goods.isBest = Convert.ToBoolean(row["是否精品"]);
                            goods.isNew = Convert.ToBoolean(row["是否新品"]);
                            goods.isTopSelling = Convert.ToBoolean(row["是否上架"]);
                            goods.isShelves = Convert.ToBoolean(row["是否热销"]);
                            goods.isPromote = Convert.ToBoolean(row["是否打折促销"]);
                            goods.isUserDiscount = Convert.ToBoolean(row["是否参与会员打折"]);
                            goods.isOrderFromFreight = Convert.ToBoolean(row["是否订单满额免运费"]);
                            goods.isDiscount = Convert.ToBoolean(row["是否订单满额打折"]);
                            goods.isTotalReduce = Convert.ToBoolean(row["是否订单满额减少"]);
                            goods.isGifts = Convert.ToBoolean(row["是否订单满额赠送礼品"]);
                            goods.isSendIntegral = Convert.ToBoolean(row["是否订单满额赠送积分"]);
                            goods.isFromFreight = Convert.ToBoolean(row["是否免运费"]);
                            goods.freightTemplate = Convert.ToInt32(row["运费模版"]);
                            DataTable goodsById = BaseFactory.theGoods.GetGoodsById(goods.id);
                            if (goodsById.Rows.Count > 0)
                            {
                                DataRow row2 = goodsById.Rows[0];
                                goods.goodsType = Convert.ToInt32(row2["goodsType"]);
                                goods.keywords = row2["keywords"].ToString();
                                goods.description = row2["description"].ToString();
                                goods.goodsRemark = row2["goodsRemark"].ToString();
                                if (BaseFactory.theGoods.Update(goods))
                                {
                                    num++;
                                    ArrayList list2 = ArrayList.Adapter(goods.category.Split(new char[] { ',' }));
                                    ArrayList list3 = new ArrayList();
                                    DataTable goodsCategoryByGoods = BaseFactory.theGoodsCategory.GetGoodsCategoryByGoods(goods.id);
                                    category = new tbGoodsCategory();
                                    category.goods = goods.id;
                                    foreach (DataRow row3 in goodsCategoryByGoods.Rows)
                                    {
                                        list3.Add(row3["category"].ToString());
                                        if (!list2.Contains(row3["category"].ToString()))
                                        {
                                            BaseFactory.theGoodsCategory.Delete(Convert.ToInt32(row3["id"]));
                                        }
                                    }
                                    foreach (string str2 in list2)
                                    {
                                        if (!list3.Contains(str2))
                                        {
                                            category.category = Convert.ToInt32(str2);
                                            BaseFactory.theGoodsCategory.Add(category);
                                        }
                                    }
                                }
                            }
                            entitys = new tbGoodsEntitys();
                            entitys.goods = goods.id;
                            entitys.barCode = row["商品条形码"].ToString();
                            entitys.goodsArtno = row["商品货号"].ToString();
                            entitys.salePrice = Convert.ToDecimal(row["销售价格"]);
                            entitys.marketPrice = Convert.ToDecimal(row["市场价格"]);
                            entitys.costPrice = Convert.ToDecimal(row["成本价格"]);
                            entitys.giveIntegral = Convert.ToInt32(row["购买商品赠送积分"]);
                            entitys.goodsWeight = Convert.ToDecimal(row["重量"]);
                            entitys.weightUnit = row["单位"].ToString();
                            entitys.integral = 0;
                            entitys.inventory = Convert.ToInt32(row["库存"]);
                            if (row["销售序号"].ToString() != "")
                            {
                                entitys.id = Convert.ToInt32(row["销售序号"]);
                                BaseFactory.theGoodsEntitys.Update(entitys);
                            }
                            else
                            {
                                BaseFactory.theGoodsEntitys.Add(entitys);
                            }
                        }
                        else
                        {
                            entitys = new tbGoodsEntitys();
                            entitys.goods = goods.id;
                            entitys.barCode = row["商品条形码"].ToString();
                            entitys.goodsArtno = row["商品货号"].ToString();
                            entitys.salePrice = Convert.ToDecimal(row["销售价格"]);
                            entitys.marketPrice = Convert.ToDecimal(row["市场价格"]);
                            entitys.costPrice = Convert.ToDecimal(row["成本价格"]);
                            entitys.giveIntegral = Convert.ToInt32(row["购买商品赠送积分"]);
                            entitys.goodsWeight = Convert.ToDecimal(row["重量"]);
                            entitys.weightUnit = row["单位"].ToString();
                            entitys.integral = 0;
                            entitys.inventory = Convert.ToInt32(row["库存"]);
                            if (row["销售序号"].ToString() != "")
                            {
                                entitys.id = Convert.ToInt32(row["销售序号"]);
                                BaseFactory.theGoodsEntitys.Update(entitys);
                            }
                            else
                            {
                                BaseFactory.theGoodsEntitys.Add(entitys);
                            }
                        }
                    }
                    else if ((((((row["商品分类"].ToString() != "") && (row["品牌"].ToString() != "")) && ((row["是否精品"].ToString() != "") && (row["是否新品"].ToString() != ""))) && (((row["是否上架"].ToString() != "") && (row["是否热销"].ToString() != "")) && ((row["是否打折促销"].ToString() != "") && (row["是否参与会员打折"].ToString() != "")))) && ((((row["是否订单满额免运费"].ToString() != "") && (row["是否订单满额打折"].ToString() != "")) && ((row["是否订单满额减少"].ToString() != "") && (row["是否订单满额赠送礼品"].ToString() != ""))) && ((row["是否订单满额赠送积分"].ToString() != "") && (row["是否免运费"].ToString() != "")))) && (row["运费模版"].ToString() != ""))
                    {
                        goods.category = row["商品分类"].ToString();
                        goods.brand = Convert.ToInt32(row["品牌"]);
                        goods.goodsName = row["商品名称"].ToString();
                        goods.goodsNo = row["商品编号"].ToString();
                        goods.origin = row["产地"].ToString();
                        goods.isBest = Convert.ToBoolean(row["是否精品"]);
                        goods.isNew = Convert.ToBoolean(row["是否新品"]);
                        goods.isTopSelling = Convert.ToBoolean(row["是否热销"]);
                        goods.isShelves = Convert.ToBoolean(row["商城上架"]);
                        goods.isProfShelves = Convert.ToBoolean(row["专区上架"]);
                        goods.isPromote = Convert.ToBoolean(row["是否打折促销"]);
                        goods.isUserDiscount = Convert.ToBoolean(row["是否参与会员打折"]);
                        goods.isOrderFromFreight = Convert.ToBoolean(row["是否订单满额免运费"]);
                        goods.isDiscount = Convert.ToBoolean(row["是否订单满额打折"]);
                        goods.isTotalReduce = Convert.ToBoolean(row["是否订单满额减少"]);
                        goods.isGifts = Convert.ToBoolean(row["是否订单满额赠送礼品"]);
                        goods.isSendIntegral = Convert.ToBoolean(row["是否订单满额赠送积分"]);
                        goods.isFromFreight = Convert.ToBoolean(row["是否免运费"]);
                        goods.freightTemplate = Convert.ToInt32(row["运费模版"]);
                        goods.goodsType = 0;
                        goods.keywords = "";
                        goods.description = "";
                        goods.goodsRemark = "";
                        goods.creator = int.Parse(base.Administrator.AdminUserId);
                        goods.id = BaseFactory.theGoods.Add(goods);
                        if (goods.id != 0)
                        {
                            id = goods.id;
                            num++;
                            Array array = goods.category.Split(new char[] { ',' });
                            category = new tbGoodsCategory();
                            foreach (string str2 in array)
                            {
                                category.goods = goods.id;
                                category.category = Convert.ToInt32(str2);
                                BaseFactory.theGoodsCategory.Add(category);
                            }
                        }
                        entitys = new tbGoodsEntitys();
                        entitys.goods = goods.id;
                        entitys.barCode = row["商品条形码"].ToString();
                        entitys.goodsArtno = row["商品货号"].ToString();
                        entitys.salePrice = Convert.ToDecimal(row["销售价格"]);
                        entitys.marketPrice = Convert.ToDecimal(row["市场价格"]);
                        entitys.costPrice = Convert.ToDecimal(row["成本价格"]);
                        entitys.giveIntegral = Convert.ToInt32(row["购买商品赠送积分"]);
                        entitys.goodsWeight = Convert.ToDecimal(row["重量"]);
                        entitys.weightUnit = row["单位"].ToString();
                        entitys.integral = 0;
                        entitys.inventory = Convert.ToInt32(row["库存"]);
                        BaseFactory.theGoodsEntitys.Add(entitys);
                    }
                    else
                    {
                        entitys = new tbGoodsEntitys();
                        entitys.goods = id;
                        entitys.barCode = row["商品条形码"].ToString();
                        entitys.goodsArtno = row["商品货号"].ToString();
                        entitys.salePrice = Convert.ToDecimal(row["销售价格"]);
                        entitys.marketPrice = Convert.ToDecimal(row["市场价格"]);
                        entitys.costPrice = Convert.ToDecimal(row["成本价格"]);
                        entitys.giveIntegral = Convert.ToInt32(row["购买商品赠送积分"]);
                        entitys.goodsWeight = Convert.ToDecimal(row["重量"]);
                        entitys.weightUnit = row["单位"].ToString();
                        entitys.integral = 0;
                        entitys.inventory = Convert.ToInt32(row["库存"]);
                        BaseFactory.theGoodsEntitys.Add(entitys);
                    }
                }
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }
                base.ClientScript.RegisterStartupScript(base.GetType(), "message", "<script language=\"javascript\" defer>alert(\"更新成功,共更新" + num + "条商品信息！\");location.href=\"goods_list.aspx\";</script>");
            }
            catch
            {
            }
        }

        protected string GetCategoryName(object category)
        {
            string str = "";
            try
            {
                ArrayList list = ArrayList.Adapter(category.ToString().Split(new char[] { ',' }));
                for (int i = 0; i < list.Count; i++)
                {
                    DataTable categoryByCategoryIdentity = BaseFactory.theCategory.GetCategoryByCategoryIdentity(Convert.ToInt32(list[i]));
                    str = str + ((i == 0) ? categoryByCategoryIdentity.Rows[0]["categoryName"].ToString() : ("," + categoryByCategoryIdentity.Rows[0]["categoryName"].ToString()));
                }
            }
            catch
            {
            }
            return str;
        }

        private void GoodsBind()
        {
            try
            {
                if (base.Request.QueryString["p"] != null)
                {
                    this.pageIndex = int.Parse(base.Request.QueryString["p"]);
                }
                if (base.Request.QueryString["ps"] != null)
                {
                    this.pageSize = Convert.ToInt32(base.Request.QueryString["ps"]);
                }
                if (base.Request.QueryString["or"] != null)
                {
                    this.order = base.Request.QueryString["or"];
                }
                if (base.Request.QueryString["ot"] != null)
                {
                    this.ot = Convert.ToInt32(base.Request.QueryString["ot"]);
                }
                if (base.Request.QueryString["agentType"] != null)
                {
                    if (base.Request.QueryString["agentType"] == "1")
                    {
                        this._agentTypeValue0 = "checked=\"checked\"";
                        this._agentTypeValue1 = "";
                    }
                    else
                    {
                        this._agentTypeValue1 = "checked=\"checked\"";
                        this._agentTypeValue0 = "";
                    }
                }
                this.pl.TblName = "view_goods";
                this.pl.StrGetFields = "id,goodsName,goodsNo,category,companyId, salePrice,isShelves,isBest,isNew,isTopSelling,inventory,isFromFreight,isnull(isProfShelves,0) as isProfShelves,inCount,outCount,realyCount,freezeCount ";
                this.pl.FldName = this.order;
                this.pl.PageSize = this.pageSize;
                this.pl.PageIndex = this.pageIndex;
                this.pl.DoCount = 1;
                this.pl.OrderType = this.ot;

                    this.pl.StrWhere = " companyId=" + base.Administrator.CompanyId;
        
                if ((base.Request.QueryString["t"] != null) && (base.Request.QueryString["kw"] != null))
                {
                    this.kw = base.Request.QueryString["kw"];
                    if (base.Request.QueryString["t"] != "categoryName")
                    {
                        this.pl.StrWhere =  this.pl.StrWhere + " and " + base.Request.QueryString["t"] + " like '%" + this.kw + "%'";
                    }
                    else
                    {
                        this.pl.StrWhere = this.pl.StrWhere +  " and id in(select goods from tb_goodsCategory a left join tb_category b on a.category=b.categoryIdentity where b.categoryName like '%" + this.kw + "%')";
                    }
                }
                else
                {
                    this.pl.StrWhere = " companyId=" + base.Administrator.CompanyId;
                }

            //    this.pl.StrWhere = this.pl.StrWhere + " and creator=" + base.Administrator.AdminUserId;

                this.total = Convert.ToInt32(BaseFactory.thePageList.GetPageList(this.pl).Rows[0]["Total"]);
                this.pl.DoCount = 0;
                DataTable pageList = BaseFactory.thePageList.GetPageList(this.pl);
                new PageListNo().DelPageSize(pageList, this.total);
                if (pageList.Rows.Count == 0)
                {
                    this.btnDelete.Visible = false;
                }
                this.rptGoods.DataSource = pageList.DefaultView;
                this.rptGoods.DataBind();
            }
            catch
            {
            }
        }

        protected override object LoadPageStateFromPersistenceMedium()
        {
            byte[] inArray = ViewStateCompression.DeCompress(Convert.FromBase64String(base.Request.Form.Get("__MSPVSTATE")));
            LosFormatter formatter = new LosFormatter();
            return formatter.Deserialize(Convert.ToBase64String(inArray));
        }

        protected void Page_Load(object sender, EventArgs e)
        {
         
            if (!base.IsPostBack)
            {
                this.ValidateLoginUser();
                this.DeletedGoods();
                if (base.Request.QueryString["t"] != null)
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sGs", "<script type=\"text/javascript\">selectIsExitItem(\"selectGoods\",\"" + base.Request.QueryString["t"] + "\");</script>");
                }
                if (base.Request.QueryString["ps"] != null)
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sPs", "<script type=\"text/javascript\">selectIsExitItem(\"selectPageSize\",\"" + base.Request.QueryString["ps"] + "\");</script>");
                }
                this.btnDelete.Attributes.Add("disabled", "disabled");
                this.GoodsBind();
            }
        }

        void ValidateLoginUser()
        {
            if(!base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsList))
            {
                base.Response.Write("<script language=javascript>window.top.location.href='../login.aspx';</script>");
                base.Response.End();
            }
            if(base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsAdd))
            {
                _addDisplay = "block";
            }
            if(base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsEdit))
            {
                _isEdit = true;
            }
            if(base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsDeleted))
            {
                _isDeleted = true;
            }
            if(base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsIn))
            {
                _isGoodsIn = true;
            }
              if(base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsOut))
            {
                _isGoodsOut = true;
            }
        }

        void DeletedGoods()
        {

            string pathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
            int goods = 0;
            if (Request.QueryString["action"] == "del")
            {
                goods = Convert.ToInt32(Request.QueryString["id"]);
                DataTable goodGalleryByGoods = BaseFactory.theGoodGallery.GetGoodGalleryByGoods(goods);
                if (BaseFactory.theGoods.Delete(goods))
                {
                    foreach (DataRow row in goodGalleryByGoods.Rows)
                    {
                        if ((row["thumbImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["thumbImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["thumbImg"].ToString()));
                        }
                        if ((row["smallImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["smallImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["smallImg"].ToString()));
                        }
                        if ((row["bigImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["bigImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["bigImg"].ToString()));
                        }
                    }
                    base.Response.Redirect(pathAndQuery.Replace("action=","noaction="));
                }
                else
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sd", "<script language=\"javascript\" defer>alert('删除失败！');</script>");
                }
            }
        }


        protected override void SavePageStateToPersistenceMedium(object pViewState)
        {
            LosFormatter formatter = new LosFormatter();
            StringWriter output = new StringWriter();
            formatter.Serialize(output, pViewState);
            string hiddenFieldInitialValue = Convert.ToBase64String(ViewStateCompression.Compress(Convert.FromBase64String(output.ToString())));
            base.ClientScript.RegisterHiddenField("__MSPVSTATE", hiddenFieldInitialValue);
        }

        protected void rptGoods_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if(!_isEdit)
                {
                  e.Item.FindControl("divEdit").Visible = false;
                }
                if (!_isDeleted)
                {
                    e.Item.FindControl("divDeleted").Visible = false;
                }
                if (!_isGoodsIn)
                {
                    e.Item.FindControl("divInStore").Visible = false;
                }
                if (!_isGoodsOut)
                {
                    e.Item.FindControl("divOutStore").Visible = false;
                }
                //if (Request.QueryString["agentType"] != "0")
                //{
                //    e.Item.FindControl("divEditMarketPrice").Visible = false;
                //}
            }
        }

    }
}